package com.xtsoft.platform.base.system.controller;

import com.fasterxml.jackson.databind.JsonMappingException;

import com.xtsoft.core.controller.GenericController;

import com.xtsoft.core.repository.QueryFilter;
import com.xtsoft.core.repository.QueryResult;
import com.xtsoft.core.utils.ResultMessage;
import com.xtsoft.core.utils.ResultMsg;
import com.xtsoft.core.utils.StringUtils;
import com.xtsoft.platform.base.system.domain.SysOrganize;
import com.xtsoft.platform.base.system.domain.SysUser;
import com.xtsoft.platform.base.system.service.SysOrganizeService;
import com.xtsoft.platform.base.system.service.SysTradeService;
import com.xtsoft.platform.globe.Constants.Constants;
import com.xtsoft.platform.globe.enums.OrganizeType;
import com.xtsoft.platform.globe.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JsonParseException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.List;

/**
 * 
 * @ClassName: SysOrganize
 *             <p>
 *             企业处理类
 *             </p>
 * @author: Codegen-代码生成器
 * @date: 2019年12月3日 上午10:59:46
 */
@Tag(name =  "企业--处理接口")
@RestController
public class SysOrganizeController extends GenericController {

	private final Logger log = LoggerFactory.getLogger(SysOrganizeController.class);



	@Autowired
	private SysOrganizeService sysOrganizeService;
	@Autowired
	private SysTradeService sysTradeService;
	/**
	 * <p>
	 * 新增一个企业
	 * </p>
	 * 
	 * @param sysOrganize
	 *            要新增的企业
	 * @return ResponseEntity<ResultMsg>, ResultMsg的Data中包含 企业
	 * @throws URISyntaxException
	 *             如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
	 * @date 2020-06-01 17:10:46
	 */
	
	@Parameter(name = "sysOrganize", description = "要新增的企业", required = false)
	@PostMapping("/sysOrganize/add")
	@Operation(summary  = "新增，根据前台传递的企业新增")
	public ResponseEntity<ResultMessage> add(
			 @RequestBody SysOrganize sysOrganize)
			throws URISyntaxException {
		if (null == sysOrganize) {
			return new ResponseEntity<ResultMessage>(new ResultMessage(false, "新增企业失败，传递的企业为空"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("新增企业开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		if (!StringUtils.isEmpty(sysOrganize.getOrganizeId())) {
			log.info("新增企业失败，新企业不能具有OrganizeId属性值", user.getLoginId(),
					user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMessage>(new ResultMessage(false, "新增企业失败，新企业不能具有OrganizeId属性值"), HttpStatus.OK);
		}
		SysOrganize sysOrganizePre = null;
		if(sysOrganize.getSysOrganizeType().getNodeId().equals(Constants.RootNode)) {
			return new ResponseEntity<ResultMessage>(new ResultMessage(false, "新增企业/部门失败，企业类型根节点不能新增企业/部门"), HttpStatus.OK);
		}
		if(sysOrganize.getParentNodeId().equals(Constants.RootNode)) {
			if(sysOrganize.getOrganizeType() == OrganizeType.Department.getIntValue()) {
				return new ResponseEntity<ResultMessage>(new ResultMessage(false, "新增企业/部门失败，根节点下不能新增部门！"), HttpStatus.OK);
			}
			sysOrganize.setParentNodeId(Constants.RootNode);
		}else {
			sysOrganizePre = sysOrganizeService.getByNodeId(sysOrganize.getParentNodeId());
			if(sysOrganizePre.getOrganizeType() == OrganizeType.Department.getIntValue() && 
					sysOrganize.getOrganizeType() == OrganizeType.Organize.getIntValue()) {
				return new ResponseEntity<ResultMessage>(new ResultMessage(false, "新增企业失败，部门下不能新增企业！"), HttpStatus.OK);
			}
			sysOrganize.setParentNodeId(sysOrganizePre.getNodeId());
		}

		
		sysOrganizeService.addSysOrganize(sysOrganize);
		//sysOrganize.setSysTrade(sysTradeService.get("04"));
		SysOrganize result = sysOrganizeService.save(sysOrganize);
		log.info("新增企业成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMessage>(new ResultMessage(true, "新增成功", result), HttpStatus.OK);
	}


	/**
	 * <p>
	 * 更新一个企业
	 * </p>
	 * 
	 * @param sysOrganize
	 *            要更新的企业
	 * @return ResponseEntity<ResultMsg>, json格式
	 * @throws URISyntaxException
	 *             如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @date 2020-06-01 17:10:46
	 */
	
	@Parameter(name = "sysOrganize", description = "要更新的企业", required = false) 
	@Operation(summary  = "更新，根据传递的 企业更新实体")
	@PostMapping("/sysOrganize/update")

	public ResponseEntity<ResultMsg> update(
			@RequestBody SysOrganize sysOrganize)
			throws URISyntaxException, IllegalAccessException, InvocationTargetException {
		if (null == sysOrganize) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "更新企业失败，传递的企业为空"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("单条更新企业开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		// 若 企业无主键值，说明调用错误
		if (StringUtils.isBlank(sysOrganize.getOrganizeId())) {
			log.info("单条更新企业失败，企业对象OrganizeId无属性值", user.getLoginId(),
					user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "更新失败，企业对象OrganizeId无属性值"), HttpStatus.OK);
		}
		SysOrganize sysOrganizePre = sysOrganizeService.getByNodeId(sysOrganize.getParentNodeId());
		if(!StringUtils.isEmpty(sysOrganizePre)) {
			if(sysOrganizePre.getOrganizeType() == OrganizeType.Department.getIntValue() && sysOrganize.getOrganizeType() == OrganizeType.Organize.getIntValue()) {
				return new ResponseEntity<ResultMsg>(new ResultMsg(false, "更新企业失败，部门下不能存在企业！",null), HttpStatus.OK);
			}
		}
		SysOrganize result = sysOrganizeService.get(sysOrganize.getOrganizeId());
		sysOrganizeService.updateSysOrganize(sysOrganize,result);
		//BeanUtil.copyNotNullProperties(sysOrganizeService.get(sysOrganize.getOrganizeId()),sysOrganize);
		
		result = sysOrganizeService.save(sysOrganize);
		log.info("单条更新企业成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "更新成功", result), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 查询企业列表，若分页，则页码信息在Request的参数中，包括当前页，每页记录数
	 * </p>
	 * 
	 * @return ResponseEntity<QueryResult<SysOrganize>>，json格式
	 * @throws URISyntaxException
	 *             如果出错，则产生页码信息的 HTTP headers
	 * @author Codegen-代码生成器
	 * @date 2020-06-01 17:10:46
	 */
	
	@Operation(summary  = "查询，根据传递的条件查询企业列表，条件参数在Request中")
	@GetMapping("/sysOrganize/getAll")
	
	public ResponseEntity<QueryResult<SysOrganize>> getAll()
			throws URISyntaxException, JsonParseException, JsonMappingException, IOException, ParseException {
		QueryFilter<SysOrganize> filter = new QueryFilter<SysOrganize>(SysOrganize.class);
		filter.addFilterFromRequest(request);
		filter.addFilter("Q_organizeType_I_NEQ",String.valueOf(OrganizeType.VirtualOrganize.getIntValue()));
		QueryResult<SysOrganize> result = sysOrganizeService.anyQuery(filter);
		return new ResponseEntity<QueryResult<SysOrganize>>(result, HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据企业唯一ID值获取企业
	 * </p>
	 * 
	 * @param id
	 *            企业唯一ID值
	 * @return ResponseEntity<SysOrganize>
	 * @author Codegen-代码生成器
	 * @date 2020-06-01 17:10:46
	 */
	@Parameter(name = "id", description = "对象唯一Id", required = false)
	@Operation(summary  = "获取单个企业，若根据企业唯一Id获取到了多个对象则发生异常")
	@GetMapping("/sysOrganize/get/{id}")
	
	
	public ResponseEntity<ResultMsg> get(
			 @PathVariable String id) {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取单个企业失败，未给定企业的唯一标识"), HttpStatus.OK);
		}

		SysOrganize sysOrganize = sysOrganizeService.get(id);
		/*
		 * <p> ofNullable执行逻辑：如果对象为空，则执行orElse，否则执行.map... return
		 * Optional.ofNullable(sysRole).map(result -> new ResponseEntity<>(result,
		 * HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
		 */

		if (null == sysOrganize) {
	
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取单个企业失败，给定的企业可能被删除"), HttpStatus.OK);
		}
	
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "获取成功", sysOrganize), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据企业唯一ID值删除单个企业
	 * </p>
	 * 
	 * @param id
	 *            企业唯一ID值
	 * @return ResponseEntity,json格式
	 * @author Codegen-代码生成器
	 * @date 2020-06-01 17:10:46
	 */
	
	@Parameter(name = "id", description = "企业唯一Id", required = false)
	@Operation(summary  = "删除单个企业")
	@GetMapping("/sysOrganize/delete/{id}")

	public ResponseEntity<ResultMsg> delete(
			 @PathVariable String id) {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "删除单个企业失败，未给定企业的唯一标识"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("删除单条企业开始......", user.getLoginId(), user.getUsername(),
				getClientIp());
		log.info("删除单条企业成功", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(sysOrganizeService.removeOrganize(id), HttpStatus.OK);
	}



	/**
	 * 功能: 根据行业查找企业 并根据规模排序
	 * 
	 * @return
	 * @return ResponseEntity<List<SysOrganize>>
	 * @throws ParseException
	 * @throws IOException
	 * @throws JsonMappingException
	 * @throws JsonParseException
	 * @date 2018年8月28日 下午2:53:03
	 * @auth kezhuan
	 */
	
	
	@Parameter(name = "tradeId",description = "行业Id",required = false)
	@Operation(summary  = "根据行业查找企业 并根据规模排序")
	@GetMapping("/sysOrganize/getMultCombox")

	
	public ResponseEntity<List<SysOrganize>> getMultCombox(
			@RequestParam(value = "tradeId", required = false) String tradeId) {
		List<SysOrganize> result = sysOrganizeService.getMultCombox(tradeId);
		return new ResponseEntity(result, HttpStatus.OK);
	}


	/**
	 * 
	 * <b>Description:启用或禁用用户</b><br>
	 * 
	 * @param ids
	 *            选择的用户ID id1,id2 逗号分隔
	 * @return
	 * @Note <b>Author:liuyang</b> <br>
	 *       <b>Date:</b>2017年8月29日 上午10:05:23 <br>
	 *       <b>Version:</b> 1.0
	 */
	@Parameter(name = "ids",description = "系统用户id集合",required = false)
	@Operation(summary  = "启用或禁用用户")
	@GetMapping("/sysOrganize/enableOrDisable/{ids}")

	public ResponseEntity<ResultMessage> enableOrDisable(@PathVariable String ids) {
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		ResultMessage resultMessage = sysOrganizeService.enableOrDisable(ids);
		log.info("给企业用户重置了状态", user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<>(resultMessage, HttpStatus.OK);
	}
	
	
    /**
     *     <p>根据企业唯一ID值集合，批量删除企业</p>
     * @param  ids 企业唯一ID值集合
     * @return ResponseEntity<ResultMsg>,返回结果中有删除的记录数，json格式
	 * @author Codegen-代码生成器
	 * @date 2020-06-01 17:10:46		 
     */
	@Parameter(name = "ids", description="逗号分隔的企业Id集合", required = false)
	@Operation(summary ="删除企业集合")
    @PostMapping("/sysOrganize/deleteBatch")
	 
    public ResponseEntity<ResultMsg> deleteBatch(@RequestParam String ids) {
		if(StringUtils.isBlank(ids)){
			 return new ResponseEntity<ResultMsg>(new ResultMsg(false,"批量删除企业失败，未给定企业的唯一标识集合"),HttpStatus.OK);
		}		
		log.info("批量删除企业开始......");
        long rows = sysOrganizeService.deleteBatch(ids);
		log.info("批量删除企业成功");
        return new ResponseEntity<ResultMsg>(new ResultMsg(true,"批量删除企业成功",rows),HttpStatus.OK);
    }
	
	
}
